#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under 
# the Apache License, Version 2.0  (the "License"); you may not use this file
# except in compliance with the License.  
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
#      contact@openairinterface.org
################################################################################
# file build_mme
# brief
# author Lionel Gauthier
# company Eurecom
# email: lionel.gauthier@eurecom.fr
#
################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
source $THIS_SCRIPT_PATH/../build/tools/build_helper.mme

function help()
{
  echo_error " "
  echo_error "Usage: build_mme [OPTION]..."
  echo_error "Build the MME executable."
  echo_error " "
  echo_error "Options:"
  echo_error "Mandatory arguments to long options are mandatory for short options too."
  echo_error "  -b, --build-type                          Build type as defined in cmake, allowed values are: Debug Release RelWithDebInfo MinSizeRel"
  echo_error "  -c, --clean                               Clean the build generated files: config, object, executable files (build from scratch)"
  echo_error "  -f, --force                               No interactive script for installation of software packages."
  echo_error "  -F, --free-diameter-unmod-ext-lib         Install freeDiameter with non modified extension library."
  echo_error "  -h, --help                                Print this help."
  echo_error "  -i, --check-installed-software            Check installed software packages necessary to build and run MME (support $SUPPORTED_DISTRO)."
  echo_error "  -s, --split-mob-git-repo  git_url         mobility git repository"
  echo_error "  -S, --split-mob-lfs-repo  directory       mobility repository accessible through a local directory path"
  echo_error "  -u, --unit-tests                          Trigger unit tests."
  echo_error "  -v, --verbose                             Make build process verbose."
  echo_error "  -V, --Verbose                             CMake only build process verbose, display compilation warnings and errors."
  echo_error " "
}

# arg1 is git URL
# global var for return value of function get_git_mobility_repo
OPENAIR_CN_MOBILITY_DIR=/tmp/openair-cn-mobility
function get_git_mobility_repo()
{
  # hardcoded path
  rm -Rf $OPENAIR_CN_MOBILITY_DIR
  git clone $1 $OPENAIR_CN_MOBILITY_DIR
  if [ $? -ne 0 ]; then
    echo_error "Failed to clone git URL $1, abort"
    return 1
  fi
  return 0
}

PIDFILE=/var/run/$NAME.pid
export FD_INSTALL_FUNC=install_opencoord.org_freediameter

function main()
{
  local -i clean=0
  local -i force=0
  local -i unit_tests=0
  local -i verbose=0
  local -i var_check_install_oai_software=0
  local    cmake_args=" "
  local    make_args="-j`nproc`"


  until [ -z "$1" ]
    do
    case "$1" in
      -b | --build-type)
        list_include_item "Debug Release RelWithDebInfo MinSizeRel" $2
        [[ $? -ne 0 ]] && echo_error "Build type $2 not recognized" && return $?
        cmake_args="$cmake_args -DCMAKE_BUILD_TYPE=$2"
        shift 2;
        ;;
      -c | --clean)
        clean=1
        echo "Clean the build generated files (build from scratch)"
        shift;
        ;;
      -f | --force)
        force=1
        echo "Force set (no interactive)"
        shift;
        ;;
      -F | --free-diameter-unmod-ext-lib)
        export FD_INSTALL_FUNC=install_freediameter_from_source
        echo "Will install old freeDiameter library"
        shift;
        ;;
      -h | --help)
        help
        shift;
        exit 0
        ;;
      -i | --check-installed-software)
        echo "Check installed software packages necessary to build and run EPC (support $SUPPORTED_DISTRO):"
        set_openair_env
        var_check_install_oai_software=1
        shift;
        ;;
      -s | --split-mob-git-repo)
        get_git_mobility_repo $2
        [[ $? -ne 0 ]] && return $?
        cmake_args="$cmake_args -DMOBILITY_REPO=True -DMOBILITY_REPO_SRC=$OPENAIR_CN_MOBILITY_DIR"
        shift 2;
        ;;
      -S | --split-mob-lfs-repo)
        if [ ! -d $2 ]; then
          echo_error "\"$2\" is not a known directory on this local file system, abort"
          return 1
        fi
        
        cmake_args="$cmake_args -DMOBILITY_REPO=True -DMOBILITY_REPO_SRC=$2"
        shift 2;
        ;;
      -u | --unit-tests)
        echo "Unit tests triggered"
        unit_tests=1
        shift;
        ;;
      -v | --verbose)
        echo "Make build process verbose"
        cmake_args="$cmake_args -DCMAKE_VERBOSE_MAKEFILE=ON"
        make_args="VERBOSE=1 $make_args"
        verbose=1
        shift;
        ;;
      -V | --Verbose)
        echo "CMake build process verbose"
        verbose=1
        shift;
        ;;
      *)   
        echo "Unknown option $1"
        help
        return 1
        ;;
    esac
  done
  
  set_openair_env 
  if [[ $verbose -eq 1 ]]; then
    cecho "OPENAIRCN_DIR    = $OPENAIRCN_DIR" $green
  fi
  
  if [ $var_check_install_oai_software -gt 0 ];then
    update_package_db
    check_install_mme_software  $force
    if [ $? -ne 0 ]; then
        echo_error "Error: MME software installation failed"
        return 1
    else
        echo_success "MME software installation successful"
        echo "MME not compiled, to compile it, re-run build_mme without -i option"
        return 0
    fi
  fi
  

  local dlog=$OPENAIRCN_DIR/build/log
  
  mkdir -m 777 -p $dlog
  
  ##############################################################################
  # Create mme
  ##############################################################################
  cd $OPENAIRCN_DIR/build
  if [ ! -d ./mme ]; then
    mkdir -m 777 -p -v mme
  fi
 
  ##############################################################################
  # Clean
  ##############################################################################
  cd $OPENAIRCN_DIR/build/mme
  if [ $clean -ne 0 ]; then
    if [[ $verbose -eq 1 ]]; then
      echo "Cleaning MME: generated configuration files, obj files, mme executable"
    fi
    rm -Rf $OPENAIRCN_DIR/build/mme/build  2>&1
    mkdir -m 777 -p -v build
  fi

  
  ##############################################################################
  # Compile MME
  ##############################################################################
  cd $OPENAIRCN_DIR/build/mme
  if [ ! -d ./build ]; then
    mkdir -m 777 -p -v build
  fi

  cd ./build
  $CMAKE $cmake_args .. > /dev/null
  ret=$?;[[ $ret -ne 0 ]] && return $ret

  compilations mme mme $OPENAIRCN_DIR/build/mme/build/mme_app $verbose
  ret=$?;[[ $ret -ne 0 ]] && return $ret

  if [ $unit_tests -ne 0 ]; then
    make_test mme mme $OPENAIRCN_DIR/build/mme/build/mme_app $verbose
    ret=$?;[[ $ret -ne 0 ]] && return $ret
  fi 

  $SUDO killall -q mme
  $SUDO cp -upv $OPENAIRCN_DIR/build/mme/build/mme_app/mme /usr/local/bin && $SUDO chmod 755 /usr/local/bin/mme && echo_success "mme installed"  
  return 0
}


main "$@"



